package job;

import model.StationTickets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import play.db.jpa.JPA;
import play.jobs.Every;
import play.jobs.Job;
import play.jobs.OnApplicationStart;

import javax.persistence.Query;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *  * @描述： TODO
 *   * @Author shiyanhe
 *    * @Date 2020/3/23 14:20
 *     */
@OnApplicationStart(async = true)
@Every("5mn")
public class StationTicketsJob extends Job {
    private static Logger log = LoggerFactory.getLogger(StationTicketsJob.class);

    @SuppressWarnings("unchecked")
    public void doJob() {
        log.info("stationtickets进入到job");
	//切库，查询最后更新时间
	JPA.setCurrentConfigName(null);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date lastsynctime = new Date();
		try {
			Query query = JPA.em().createNativeQuery("select count(*) as num, max(scsj) from stationtickets ");
		    Object[] rs = (Object[]) query.getSingleResult();
			if(Integer.parseInt(rs[0].toString())==0){
				lastsynctime = sdf.parse("2023-07-01 00:00:00");
			}else if(rs[1]!=null){
				lastsynctime = (Date) rs[1];
			}
			log.info("stationtickets同步---查询到最后更新时间为：" +sdf.format(lastsynctime));
		} catch (Exception e) {
			log.error("查询jcfx_jcfxticketsell数据失败,将使用当前时间！" , e);
		}       

	//切换至国税数据库查询线下车票数据
        JPA.setCurrentConfigName("guoshui");
        StringBuffer sb = new StringBuffer();
        StationTickets stationTickets = new StationTickets();
        List<StationTickets> list = new ArrayList<StationTickets>();
//      sb.append("select * from t_sjzx_kpscsj where scsj between '2023-6-29 00:00:00' and '2023-6-30 00:00:00' ");
//	sb.append("select * from t_sjzx_kpscsj where scsj between date_add(NOW(), interval -3 hour) and NOW()");	
	sb.append("select * from t_sjzx_kpscsj where scsj between date_add(:lastsynctime, interval -3 hour) and NOW()");
	try {
            Query query = JPA.em().createNativeQuery(sb.toString(), StationTickets.class);
            query.setParameter("lastsynctime", lastsynctime);
	    list = query.getResultList();

        } catch (Exception e) {
            play.Logger.applogErrorDetail(e, null, "stationTicketsJob", false, "查询国税数据库失败", null, null, null);
        }
        
	JPA.setCurrentConfigName(null);

	play.Logger.info("stationtickets插入数据 " + list.size());

	 for (int i = 0; i < list.size(); i++) {
            if (!JPA.em().getTransaction().isActive()) {
                JPA.em().getTransaction().begin();
            }
            String deleteSql = "delete from stationtickets where xh = :xh and kyzbh=:kyzbh ";
            try {
                Query query1 = JPA.em().createNativeQuery(deleteSql);
                query1.setParameter("xh", list.get(i).xh).setParameter("kyzbh", list.get(i).kyzbh)

                        .executeUpdate();
                JPA.em().persist(list.get(i));
            } catch (Exception e) {
                play.Logger.applogErrorDetail(e, null, "stationTicketsJob", false, "删除、新增数据失败", null, null, null);
                JPA.em().getTransaction().rollback();
                continue;
            }
            if (JPA.em().getTransaction().isActive()) {
                try {
                    JPA.em().getTransaction().commit();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
        log.info("stationticketsjob执行完毕");
    }
}



